package IPFS

import (
	"errors"
	"fmt"
	shell "github.com/ipfs/go-ipfs-api"
	"io"
	"ipfs-browser/src/tool"
	"os"
)

func createShell() *shell.Shell {
	cfg, err := tool.ParseConfig("./config/app.json")
	if err != nil {
		panic(err)
	}
	ipfs_cfg := cfg.IPFSAPI
	url := ipfs_cfg.Host + ":" + ipfs_cfg.Port
	sh := shell.NewShell(url)
	return sh
}
func Upload(path string) (string, error) {
	f, err := os.Open(path)
	if err != nil {
		panic(err)
	}
	defer f.Close()
	var reader io.Reader = f
	sh := createShell()
	cid, err := sh.Add(reader)
	return cid, err
}

func Download(cid string, path string) {
	sh := createShell()
	rc, err := sh.Cat(cid)
	if err != nil {
		fmt.Println("sdf")
		panic(err)
	}
	if path == "" {
		path = "./.cache/" + cid
	}
	file, err := os.Create(path)
	if err != nil {
		panic(err)
	}
	defer file.Close()
	_, err = io.Copy(file, rc)
	if err != nil {
		panic(err)
	}
	fmt.Println(path)
}

func Upload_folder(dir string) (string, error) {
	sh := createShell()
	if _, err := os.Stat(dir); errors.Is(err, os.ErrNotExist) {
		// path/to/whatever does not exist
		fmt.Println("Dir does not eixst")
	}
	cid, err := sh.AddDir(dir)
	return cid, err
}

func Download_folder(cid, outdir string) error {
	sh := createShell()
	err := sh.Get(cid, outdir)
	return err
}
